//
//  CYInvestRecordViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/18.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYInvestRecordViewController.h"

#import "CYInvestRecordCell.h"

#import "CYInvestRecordDetailViewController.h"
#import "CYMainController.h"



@interface CYInvestRecordViewController ()

@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UIView *topLine;
@property(nonatomic, strong)UILabel *waitTitle;
@property(nonatomic, strong)UILabel *repaymentTitle;
@property(nonatomic, strong)UIView *currentLine;
@property(nonatomic, strong)UILabel *currentTitle;
@property(nonatomic, strong)UIButton *waitButton;
@property(nonatomic, strong)UIButton *repaymentButton;

@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)UITableView *waitTableView;
@property(nonatomic, strong)NIMutableTableViewModel *waitTableModel;
@property(nonatomic, strong)UITableView *repaymentTableView;
@property(nonatomic, strong)NIMutableTableViewModel *repaymentTableModel;

@property(nonatomic, strong)UIView *noneView;
@property(nonatomic, strong)UIImageView *noneImageView;
@property(nonatomic, strong)UILabel *noneLabel;
@property(nonatomic, strong)UIButton *noneButton;

@property(nonatomic, strong)UIView *maskView;

@property(nonatomic, assign)NSInteger page_no_wait;
@property(nonatomic, assign)BOOL loading_wait;
@property(nonatomic, assign)BOOL hasMore_wait;
@property(nonatomic, assign)BOOL noData_wait;
@property(nonatomic, assign)BOOL firstComplete_wait;

@property(nonatomic, assign)NSInteger page_no_repayment;
@property(nonatomic, assign)BOOL loading_repayment;
@property(nonatomic, assign)BOOL hasMore_repayment;
@property(nonatomic, assign)BOOL noData_repayment;
@property(nonatomic, assign)BOOL firstComplete_repayment;
@end


@implementation CYInvestRecordViewController

- (void)loadDataFromServer_wait
{
    if(self.loading_wait)
    {
        return;
    }
    if(self.hasMore_wait == NO)
    {
        return;
    }
    self.loading_wait = YES;
    @weakify(self);
    [CYStandardDataAPI user_queryAllInvestDetailWithPage_no:@(self.page_no_wait) status:CYDataAPIInvestRecordStatusNormal complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if([response.content isKindOfClass:[NSArray class]])
            {
                if([response.content count] == 0 && self.page_no_wait == 1)
                {
                    self.noData_wait = YES;
                }
                else
                {
                    self.hasMore_wait = [response.content count] >= CY_API_PAGE_SIZE;
                    self.page_no_wait ++;
                    NSMutableArray *cells = [NSMutableArray array];
                    for(NSDictionary *record in response.content)
                    {
                        CYInvestRecordCellObject *cell = [CYInvestRecordCellObject objectWithCellClass:[CYInvestRecordCell class]];
                        cell.iid = SAFE_NUMBER(record[@"id"]);
                        cell.title = SAFE_STRING(record[@"projectTitle"]);
                        cell.dueDay = SAFE_NUMBER(record[@"dueDay"]);
                        cell.capital = SAFE_NUMBER(record[@"invSucc"]);
                        cell.profits = SAFE_NUMBER(record[@"waitInterest"]);
                        cell.investDate = [[SAFE_NUMBER(record[@"addTime"]) cy_date] cy_stringWithFormat:@"yyyy-MM-dd"];
                        cell.dueDate = [[SAFE_NUMBER(record[@"dueTime"]) cy_date] cy_stringWithFormat:@"yyyy-MM-dd"];
                        [cells addObject:cell];
                    }
                    [self.waitTableModel addObjectsFromArray:cells];
                    [self.waitTableView reloadData];
                }
            }
            else
            {
                self.noData_wait = YES;
            }
        }
        else
        {
            if(self.page_no_wait == 1)
            {
                self.noData_wait = YES;
            }
        }
        self.firstComplete_wait = YES;
        [self checkEmpty];
        self.loading_wait = NO;
    }];
}

- (void)loadDataFromServer_repayment
{
    if(self.loading_repayment)
    {
        return;
    }
    if(self.hasMore_repayment == NO)
    {
        return;
    }
    self.loading_repayment = YES;
    @weakify(self);
    [CYStandardDataAPI user_queryAllInvestDetailWithPage_no:@(self.page_no_repayment) status:CYDataAPIInvestRecordStatusComplete complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if([response.content isKindOfClass:[NSArray class]])
            {
                if([response.content count] == 0 && self.page_no_repayment == 1)
                {
                    self.noData_repayment = YES;
                }
                else
                {
                    self.hasMore_repayment = [response.content count] >= CY_API_PAGE_SIZE;
                    self.page_no_repayment ++;
                    NSMutableArray *cells = [NSMutableArray array];
                    for(NSDictionary *record in response.content)
                    {
                        CYInvestRecordCellObject *cell = [CYInvestRecordCellObject objectWithCellClass:[CYInvestRecordCell class]];
                        cell.iid = SAFE_NUMBER(record[@"id"]);
                        cell.title = SAFE_STRING(record[@"projectTitle"]);
                        cell.capital = SAFE_NUMBER(record[@"invSucc"]);
                        cell.profits = SAFE_NUMBER(record[@"waitInterest"]);
                        cell.investDate = [[SAFE_NUMBER(record[@"addTime"]) cy_date] cy_stringWithFormat:@"yyyy-MM-dd"];
                        cell.dueDate = [[SAFE_NUMBER(record[@"dueTime"]) cy_date] cy_stringWithFormat:@"yyyy-MM-dd"];
                        [cells addObject:cell];
                    }
                    [self.repaymentTableModel addObjectsFromArray:cells];
                    [self.repaymentTableView reloadData];
                }
            }
            else
            {
                self.noData_repayment = YES;
            }
        }
        else
        {
            if(self.page_no_repayment == 1)
            {
                self.noData_repayment = YES;
            }
        }
        self.firstComplete_repayment = YES;
        [self checkEmpty];
        self.loading_repayment = NO;
    }];
}

- (void)checkEmpty
{
    if(self.firstComplete_wait && self.firstComplete_repayment)
    {
        if(self.noData_wait && self.noData_repayment)
        {
            self.scrollView.hidden = YES;
            self.topView.hidden = YES;
            self.noneView.hidden = NO;
        }
        else
        {
            self.scrollView.hidden = NO;
            self.topView.hidden = NO;
            self.noneView.hidden = YES;
        }
    }
}

- (void)loadUI
{
    self.navigationItem.title = @"投资记录";
    self.tableView.hidden = YES;
    
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.topView];
    {
        self.topLine = [UIView cy_lineWithColor:HEXCOLOR(@"ECECEC")];
        [self.topView addSubview:self.topLine];
        
        self.waitTitle = [self titleLabelWithText:@"待还款"];
        [self.topView addSubview:self.waitTitle];
        
        self.repaymentTitle = [self titleLabelWithText:@"已还款"];
        [self.topView addSubview:self.repaymentTitle];
        
        self.currentTitle = self.waitTitle;
        self.currentTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        self.currentTitle.alpha = 1;
        
        self.currentLine = [UIView cy_lineWithColor:HEXCOLOR(@"444444")];
        [self.topView addSubview:self.currentLine];
        
        self.waitButton = [[UIButton alloc] init];
        [self.waitButton addTarget:self action:@selector(onWaitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:self.waitButton];
        
        self.repaymentButton = [[UIButton alloc] init];
        [self.repaymentButton addTarget:self action:@selector(onRepaymentButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:self.repaymentButton];
    }
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    [self.contentView addSubview:self.scrollView];
    {
        self.waitTableView = [self createTableView];
        [self.scrollView addSubview:self.waitTableView];
        
        self.repaymentTableView = [self createTableView];
        [self.scrollView addSubview:self.repaymentTableView];
    }
    
    self.noneView = [[UIView alloc] init];
    [self.contentView addSubview:self.noneView];
    {
        self.noneImageView = [[UIImageView alloc] initWithImage:CYImage(@"invest_record_none")];
        [self.noneView addSubview:self.noneImageView];
        
        self.noneLabel = [[UILabel alloc] init];
        self.noneLabel.text = @"您还未投资哦，赶紧去投资吧！";
        self.noneLabel.textColor = HEXCOLOR(@"999999");
        self.noneLabel.font = [UIFont systemFontOfSize:16];
        [self.noneLabel sizeToFit];
        [self.noneView addSubview:self.noneLabel];
        
        self.noneButton = [UIButton cy_mainButtonWithTitle:@"去投资"];
        [self.noneButton addTarget:self action:@selector(onNoneButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.noneView addSubview:self.noneButton];
    }
    
    self.maskView = [[UIView alloc] init];
    [self.contentView addSubview:self.maskView];
    
    self.scrollView.hidden = YES;
    self.topView.hidden = YES;
    self.noneView.hidden = YES;
}

- (void)loadData
{
    self.scrollView.hidden = YES;
    self.topView.hidden = YES;
    self.noneView.hidden = YES;
    
    self.page_no_wait = 1;
    self.page_no_repayment = 1;
    self.loading_wait = NO;
    self.loading_repayment = NO;
    self.hasMore_wait = YES;
    self.hasMore_repayment = YES;
    self.noData_wait = NO;
    self.noData_repayment = NO;
    self.firstComplete_wait = NO;
    self.firstComplete_repayment = NO;
    
    self.waitTableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:@[] delegate:(id)[NICellFactory class]];
    self.repaymentTableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:@[] delegate:(id)[NICellFactory class]];
    
    self.waitTableView.dataSource = self.waitTableModel;
    self.repaymentTableView.dataSource = self.repaymentTableModel;
    
    [self loadDataFromServer_wait];
    [self loadDataFromServer_repayment];
}

- (void)layoutUI
{
    self.topView.width = self.contentView.width;
    self.topView.height = 50;
    self.topView.left = 0;
    self.topView.top = 0;
    {
        self.topLine.width = self.topView.width;
        self.topLine.height = 1 / SCREEN_SCALE;
        self.topLine.left = 0;
        self.topLine.bottom = self.topView.height;
        
        self.waitTitle.centerY = self.topView.height / 2;
        self.waitTitle.centerX = self.topView.width / 4;
        
        self.repaymentTitle.centerY = self.topView.height / 2;
        self.repaymentTitle.centerX = self.topView.width * 3 / 4;
        
        self.currentLine.height = 2;
        self.currentLine.width = self.currentTitle.width - 4;
        self.currentLine.bottom = self.topView.height;
        self.currentLine.centerX = self.currentTitle.centerX;
        
        self.waitButton.width = self.topView.width / 2;
        self.waitButton.height = self.topView.height;
        self.waitButton.top = 0;
        self.waitButton.left = 0;
        
        self.repaymentButton.frame = self.waitButton.frame;
        self.repaymentButton.left = self.waitButton.right;
    }
    
    self.scrollView.width = self.contentView.width;
    self.scrollView.height = self.contentView.height - self.topView.bottom;
    self.scrollView.left = 0;
    self.scrollView.top = self.topView.bottom;
    self.scrollView.contentSize = CGSizeMake(self.scrollView.width * 2, self.scrollView.height);
    {
        self.waitTableView.frame = self.scrollView.bounds;
        self.waitTableView.top = 0;
        self.waitTableView.left = 0;
        
        self.repaymentTableView.frame = self.scrollView.bounds;
        self.repaymentTableView.top = 0;
        self.repaymentTableView.left = self.waitTableView.right;
    }
    
    self.noneView.frame = self.contentView.bounds;
    {
        self.noneImageView.centerX = self.noneView.width / 2;
        self.noneImageView.bottom = 175;
        
        self.noneLabel.centerX = self.noneView.width / 2;
        self.noneLabel.centerY = 193;
        
        self.noneButton.width = self.noneView.width - 40;
        self.noneButton.height = 44;
        self.noneButton.top = 241;
        self.noneButton.centerX = self.noneView.width / 2;
    }
    
    self.maskView.width = 20;
    self.maskView.height = self.contentView.height;
    self.maskView.left = 0;
    self.maskView.top = 0;
}

#pragma mark - Actions
- (void)detailActionWithRid:(NSNumber *)iid
{
    CYInvestRecordDetailViewController *investRecordDetailViewController = [[CYInvestRecordDetailViewController alloc] init];
    investRecordDetailViewController.iid = iid;
    [self.navigationController pushViewController:investRecordDetailViewController animated:YES];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CYInvestRecordCellObject *cellObject = nil;
    if(tableView == self.waitTableView)
    {
        cellObject = [self.waitTableModel objectAtIndexPath:indexPath];
    }
    if(tableView == self.repaymentTableView)
    {
        cellObject = [self.repaymentTableModel objectAtIndexPath:indexPath];
    }
    if(cellObject)
    {
        [self detailActionWithRid:cellObject.iid];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.scrollView)
    {
        if(self.topView.userInteractionEnabled == NO)
        {
            self.waitTitle.alpha = MIN(1, MAX(0.545, 1 - (ABS(scrollView.contentOffset.x) / scrollView.width) * 0.455));
            self.repaymentTitle.alpha = MIN(1, MAX(0.545, 1 - (ABS(scrollView.contentOffset.x - scrollView.width) / scrollView.width) * 0.455));
            self.currentLine.centerX = (scrollView.contentOffset.x / (scrollView.contentSize.width - scrollView.width) * 2 + 1) / 4 * self.topView.width;
        }
    }
    if(scrollView == self.waitTableView)
    {
        if(scrollView.contentSize.height - scrollView.contentOffset.y < scrollView.height * 2)
        {
            [self loadDataFromServer_wait];
        }
    }
    if(scrollView == self.repaymentTableView)
    {
        if(scrollView.contentSize.height - scrollView.contentOffset.y < scrollView.height * 2)
        {
            [self loadDataFromServer_repayment];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if(scrollView == self.scrollView)
    {
        self.topView.userInteractionEnabled = NO;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(scrollView == self.scrollView)
    {
        if(!decelerate)
        {
            self.topView.userInteractionEnabled = YES;
            [self checkCurrentTitle];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView == self.scrollView)
    {
        self.topView.userInteractionEnabled = YES;
        [self checkCurrentTitle];
    }
}

#pragma mark - Control Events
- (void)onWaitButtonTouchUpInside
{
    if(self.currentTitle == self.waitTitle)
    {
        return;
    }
    [self animateToTitle:self.waitTitle];
}

- (void)onRepaymentButtonTouchUpInside
{
    if(self.currentTitle == self.repaymentTitle)
    {
        return;
    }
    [self animateToTitle:self.repaymentTitle];
}

- (void)onNoneButtonTouchUpInside
{
    [[CYMainController standardController] goFinance];
}

#pragma mark - Private Method
- (UILabel *)titleLabelWithText:(NSString *)text
{
    UILabel *label = [[UILabel alloc] init];
    label.textColor = HEXCOLOR(@"444444");
    label.alpha = 0.545;
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16];
    [label sizeToFit];
    label.width += 4;
    label.height += 4;
    return  label;
}

- (UITableView *)createTableView
{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 5)];
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 5)];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    return tableView;
}

- (void)checkCurrentTitle
{
    self.waitTitle.alpha = 0.545;
    self.repaymentTitle.alpha = 0.545;
    UILabel *title = nil;
    if(self.scrollView.contentOffset.x == self.waitTableView.left)
    {
        title = self.waitTitle;
    }
    else
    {
        title = self.repaymentTitle;
    }
    self.currentTitle.font = [UIFont systemFontOfSize:16];
    self.currentTitle = title;
    self.currentTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.currentTitle.alpha = 1;
    self.currentLine.centerX = self.currentTitle.centerX;
}

- (void)animateToTitle:(UILabel *)title
{
    APP_LOCK_USER_INTERACTION;
    @weakify(self);
    CGFloat targetX = 0;
    if(title == self.repaymentTitle)
    {
        targetX = self.repaymentTableView.left;
    }
    [UIView animateWithDuration:0.25
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         @strongify(self);
                         self.currentLine.centerX = title.centerX;
                         self.scrollView.contentOffset = CGPointMake(targetX, 0);
                         self.currentTitle.alpha = 0.545;
                         title.alpha = 1;
                     }
                     completion:^(BOOL finished) {
                         @strongify(self);
                         self.currentTitle.font = [UIFont systemFontOfSize:16];
                         self.currentTitle = title;
                         self.currentTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
                         APP_UNLOCK_USER_INTERACTION;
                     }];
}

@end
